#include "camerahandler.h"
#include <QCameraInfo>
#include <QBuffer>

VideoSurface::VideoSurface(QObject *parent) : QAbstractVideoSurface(parent)
{


}

QList<QVideoFrame::PixelFormat> VideoSurface::supportedPixelFormats(QAbstractVideoBuffer::HandleType) const
{
    // 返回图像的处理格式
    return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB32;
}

bool VideoSurface::present(const QVideoFrame &frame)
{
    // 当前帧捕获
    emit this->videoChanged(frame);
    return true;
}

/*=================================================================*/

CameraHandler::CameraHandler(QObject *parent) : QObject(parent), camera(new QCamera(parent))
{
    QCameraInfo info = QCameraInfo::defaultCamera(); // 返回默认相机
    camera = new QCamera(info, this);
    timer = new QTimer(this);

    VideoSurface *vf = new VideoSurface(this); // 生成摄像头捕获格式对象

    camera->setViewfinder(vf); // 设置捕获格式
    connect(vf, &VideoSurface::videoChanged, this, &CameraHandler::onVideoChanged);
    connect(timer, &QTimer::timeout, this, &CameraHandler::onTimerout);

    timer->start(1000);
//    camera->start();
    setImageQuality(40);
}

void CameraHandler::setImageQuality(int value)
{
    imageQuality = value; // 设置图片质量
}

void CameraHandler::onBtnChange()
{
    if (camera->state() == QCamera::ActiveState)
    {
        camera->stop();
        fps = 0;
        emit getFps(0);
        emit cameraChanged(QCamera::LoadedState);
    }
    else
    {
        camera->start();
        emit cameraChanged(QCamera::ActiveState);
    }
}

void CameraHandler::onVideoChanged(QVideoFrame curframe)
{
    static int i = 0;
    QVideoFrame frame(curframe);
    frame.map(QAbstractVideoBuffer::ReadOnly);

    // 通过当前帧的对象构建QImage图片对象
    QImage image(frame.bits(),
                 frame.width(), frame.height(),
                 QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat()));

    frame.unmap();

    // 旋转图像180
    QMatrix matrix;
    matrix.rotate(180);
    image = image.transformed(matrix);
    image = image.scaled(475, 385, Qt::KeepAspectRatio, Qt::SmoothTransformation); // 160*160像素

    if((i % 1) == 0)
    {
        QByteArray byteArray;
        QBuffer buffer(&byteArray);
        buffer.open(QIODevice::WriteOnly);

        // 设置压缩质量(0-100, 数值越大质量越高)
        int quality = this->imageQuality;

        // 将压缩后的图片数据写入QBuffer
        image.save(&buffer, "JPG", quality);

        // 关闭 QBuffer
        buffer.close();


        // 重新加载压缩后的数据为 QImage
        QImage loadedImage;
        loadedImage.loadFromData(byteArray);

        //qDebug() << "压缩前:" << image.sizeInBytes() << " 压缩后:" << byteArray.size() << "变化后:" << loadedImage.sizeInBytes();
        emit sendVideo(byteArray);
        emit videoUpdate(loadedImage);
        ++fps;
    }
    i++;
}

void CameraHandler::onTimerout()
{
    emit getFps(fps);
    fps = 0;
}




